import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {injectIntl} from '../intl';
import {Upload, Icon, message, Modal} from 'antd';
import {FILES_API} from '../../constants';
import style from '../../style.css';
import ShowImg from './ShowImg';
const basePath = fetch.basePath || '';

class ImageUpload extends PureComponent {
    static getDerivedStateFromProps(props, state) {
        if(state.default && props.fileList.length)
            return {
                fileList: props.fileList.map((item, index) => ({
                    url: item.url ? item.url : `${FILES_API.files}/${item.fileId}`,
                    uid: item.fileId,
                    id: item.fileId,
                    name: item.fileName,
                    status: 'done',
                    index
                })),
                default: false
            };
        return null;
    }
    state = {
        loading: false,
        fileList: [],
        default: true,
        previewVisible: false,
        previewImage: '',
        previewImageName: ''
    }
    handleBeforeUpload = file => {
        const isLt50M = file.size / 1024 / 1024 < 50;
        if(!isLt50M)
            message.error(this.props.intl.formatMessage({
                id: 'fileUpload.message.fileSize',
                defaultMessage: '文件大小不能大于50MB'
            }));
        // 只能上传图片格式
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isBMP = file.type === 'image/bmp';
        const isGIF = file.type === 'image/gif';
        const isWEBP = file.type === 'image/webp';
        const isPic = isJPG || isPNG || isBMP || isGIF || isWEBP;
        if(!isPic)
            message.error(this.props.intl.formatMessage({
                id: 'fileUpload.message.fileSize11',
                defaultMessage: '只能上传图片'
            }));
        return isPic && isLt50M;
    }

    handleChange = ({file, fileList}) => {
        if(file.status === 'uploading')
            this.setState({loading: true});

        if(file.status === 'done') {
            const fileInfo = file.response.payload[0];
            this.setState({
                loading: false
            });
            this.props.onChange(fileInfo);
            message.success(this.props.intl.formatMessage({
                id: 'fileUpload.message.success',
                defaultMessage: '上传成功'
            }));
            const fileIndex = fileList.findIndex(f => f.uid === file.uid);
            fileList[fileIndex].id = file.response.payload[0].id;
        }
        if(file.status === 'error') {
            this.setState({
                loading: false
            });
            message.error(this.props.intl.formatMessage({
                id: 'fileUpload.message.fail',
                defaultMessage: '上传失败'
            }));
        }
        this.setState({fileList: file.status ? [...fileList] : this.state.fileList});
    }

    handleCancel = () => {
        this.setState({previewVisible: false});
    }
    handlePreview = async file => {
        const index = this.state.fileList.findIndex(v => v.id === file.id);
        this.setState({
            previewImage: file.id,
            previewImageName: file.name,
            previewVisible: true,
            index: file.index
        });
        this.props.updateIndex(index);
    }
    render() {
        const {previewVisible, previewImage, previewImageName} = this.state;
        const fileList = this.state.fileList.map(f => {
            if(f.id)
                return Object.assign({}, f, {
                    url: `${FILES_API.files}/${f.id}`
                });
            return f;
        });
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">{this.props.intl.formatMessage({
                    id: 'fileUpload.message.upload',
                    defaultMessage: '图片Upload'
                })}</div>
            </div>
        );
        return (
            <div>
                <div className="ant-col-width">
                    <Upload
                        accept=".jpg, .jpeg, .png"
                        action={`${basePath}${FILES_API.files}`}
                        listType="picture-card"
                        multiple={true}
                        beforeUpload={this.handleBeforeUpload}
                        showUploadList={{
                            showPreviewIcon: true,
                            showRemoveIcon: this.props.isUpload,
                            showDownloadIcon: true
                        }}
                        fileList={fileList}
                        onRemove={this.props.isUpload ? this.props.onRemove : false}
                        onPreview={this.handlePreview}
                        onChange={this.props.isUpload ? this.handleChange : false} >
                        {this.props.isUpload ? uploadButton : null}
                    </Upload>
                </div>
                {/* <Modal
                    visible={previewVisible}
                    footer={null}
                    onCancel={this.handleCancel} >
                    <img
                        style={{width: '100%'}}
                        alt={previewImage}
                        src={`${basePath}${FILES_API.files}/${previewImage}`}
                        data-src={`${basePath}${FILES_API.files}/${previewImage}`} />
                    <a icon="download" download href={`${FILES_API.files}/${previewImage}`} size="small">
                        {previewImageName}</a>
                </Modal> */}
                <ShowImg
                    data={this.props.fileList}
                    firstIndex={this.state.index || 0}
                    previewImage={this.state.previewImage}
                    showimgs={previewVisible}
                    toggleshow={this.handleCancel}>
                </ShowImg>
            </div>
        );
    }
}
ImageUpload.defaultProps = {
    isUpload: true
};
ImageUpload.propTypes = {
    fileList: PropTypes.array,
    intl: PropTypes.object,
    isUpload: PropTypes.bool,
    updateIndex: PropTypes.func,
    onChange: PropTypes.func,
    onRemove: PropTypes.func,
};
import {connect} from 'react-redux';
import {updateIndex} from '../actions';

const mapDispatchToProps = (dispatch, props) => ({
    updateIndex: data => dispatch(updateIndex(data)),
});
export default connect(null, mapDispatchToProps)(injectIntl(ImageUpload));
